package edu.gatech.mobile.scene.ui.manage;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.drawable.BitmapDrawable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import edu.gatech.mobile.scene.R;
import edu.gatech.mobile.scene.provider.impl.ImageInfoDBImpl;
import edu.gatech.mobile.scene.provider.impl.ImageInfoTable;

public class ImageListAdapter extends BaseAdapter{

	Activity mActivity;
	private static LayoutInflater inflater = null;
	List<String> images;
	List<Boolean> imageUse;
	
	
	public ImageListAdapter(Activity context){
		this. mActivity = context;
		inflater=mActivity.getLayoutInflater();
		images = new ArrayList<String>();
		imageUse = new ArrayList<Boolean>();
		
		
		Cursor cursor = new ImageInfoDBImpl(context).getAllImagesCursor();
		while (cursor != null && cursor.getCount() > 0 && !cursor.isLast()){
			cursor.moveToNext();
			String fileName=cursor.getString(cursor.getColumnIndex(ImageInfoTable.FILE_NAME));
			images.add(fileName);
			int useInt = cursor.getInt(cursor.getColumnIndex(ImageInfoTable.USE));
			Boolean use = (useInt!=0)?true:false;
			imageUse.add(use);
		}
		safelyCloseCursor(cursor);
		
	}
	
	@Override
	public int getCount() {
		return images.size();
	}

	@Override
	public String getItem(int position) {
		return images.get(position);
	}

	@Override
	public long getItemId(int position) {
		return position;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		String imageInfo = images.get(position);
		View view = convertView;
		if(convertView==null){
			view = inflater.inflate(R.layout.image_list_adapter_item, null);
		}
		TextView imgNameView =(TextView) view.findViewById(R.id.image_name);
		imgNameView.setText(imageInfo);
		if(imageUse.get(images.indexOf(imageInfo))){
			imgNameView.setTextColor(Color.GREEN);
		}
		else{
			imgNameView.setTextColor(Color.RED);
		}
		
		ImageView iconView = (ImageView) view.findViewById(R.id.image_icon);
		Bitmap image = BitmapFactory.decodeFile(imageInfo);
		if(image!=null){
			float scaleWidth = 0.2f;
			float scaleHeight = 0.2f;
			Matrix mat = new Matrix();
			mat.postScale(scaleWidth, scaleHeight);
			Bitmap resizedBitmap = Bitmap.createBitmap(image, 0, 0, image.getWidth(),
					image.getHeight(), mat, true);
			BitmapDrawable bmd = new BitmapDrawable(resizedBitmap);
			iconView.setImageDrawable(bmd);
		}
		return view;
	}
	
	private void safelyCloseCursor(Cursor cur) {
		if(cur != null && cur.isClosed() == false)
			cur.close();
	}

}
